<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">
        <span @click="handleEmit">首页</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>个人中心</el-breadcrumb-item>
      <el-breadcrumb-item>设置</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-form
        :model="editForm"
        :rules="eidtRules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            action="http://127.0.0.1/upload"
            :on-success="handleAvatarSuccess"
            name="avator"
            :headers="headerObj"
            :show-file-list="false"
          >
            <img v-if="avator" :src="avator" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <el-button
            size="mini"
            class="preview"
            @click="handlePictureCardPreview"
            >点击预览</el-button
          >
          <!-- 预览对话框 -->
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="avator" alt="" />
          </el-dialog>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="editForm.username"
            :readonly="role !== 'admin'"
          ></el-input>
        </el-form-item>
      </el-form>

      <el-button type="success" @click="saveUserInfo">保存</el-button>
    </el-card>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from 'vuex'
export default {
  async mounted() {
    // 发送请求获取用户信息
    await this.getUserInfo()
    // 给将要提交的表单赋上初始值，从vuex中拿到
    this.editForm.username = this.username
    this.editForm.avator = this.avator.replace('http://127.0.0.1', '')
  },
  data() {
    return {
      // 图片上传的请求头
      headerObj: {
        Authorization: window.localStorage.getItem('token')
      },
      editForm: {
        username: '',
        avator: ''
      },
      imgUrl: '',
      eidtRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 2,
            max: 16,
            message: '用户名长度不能小于2个字符，大于16个字符',
            trigger: 'blur'
          }
        ]
      },
      // 预览对话框
      dialogVisible: false
    }
  },
  methods: {
    ...mapMutations(['saveAvator', 'saveUname']),
    ...mapActions(['getUserInfo']),
    handleEmit() {
      this.$emit('handleNavChange')
    },
    // 图片上传成功
    handleAvatarSuccess(res, file) {
      if (res.err) {
        return this.$message.error(res.msg)
      }

      // 更新vuex中的头像数据
      this.saveAvator(`http://127.0.0.1${res.path}`)

      // 让表单中的avator等于图片路径（不用拼接）
      this.editForm.avator = res.path
    },
    // 保存用户信息
    async saveUserInfo() {
      const { data: res } = await this.$http.put(
        `/users/edit/${this.uid}`,
        this.editForm
      )
      if (res.meta.status !== 200) {
        return this.$message.error('保存失败')
      }
      this.$message.success('保存成功')
      // 更新vuex中的用户信息
      this.saveUname(this.editForm.username)
    },

    // 显示预览图片对话框
    handlePictureCardPreview() {
      this.dialogVisible = true
    }
  },
  computed: {
    ...mapState(['role', 'uid', 'avator', 'username'])
  }
}
</script>

<style lang="less" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9 !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.el-form-item {
  display: flex;
  align-items: center;
}
.el-button {
  margin-left: 38px;
  margin-top: 25px;
}
.preview {
  margin-left: 45px;
  margin-top: 0;
}
</style>
